package com.baomidou.kisso.web.controller;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.dto.Result;
import com.baomidou.kisso.dto.ResultCode;
import com.baomidou.kisso.dto.ResultGenerator;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.kisso.service.ym.AccountService;
import com.baomidou.kisso.service.ym.CookieService;
import com.baomidou.kisso.service.ym.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一登录
 *
 * @author : fuminwang
 * @Description :
 * @CreateDate : 2018/01/02 14:26
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    TokenService tokenService;
    @Autowired
    AccountService accountService;
    @Autowired
    CookieService cookieService;


    @GetMapping
    @ResponseBody
    @Login(action = Action.Skip)
    public Result login(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String account = "13718102718";
        String password = "ruby1207";
        //1.获取token
        String token = tokenService.getToken();
        //2.校验用户是否存在
        if(token!=null && token!=""){
            //校验用户是否存在
            Result accountResult = accountService.verification(token,account,password);
            if(accountResult.getCode()!= ResultCode.SUCCESS.code){
                return accountResult;
            }
            //3保存cookie
            SSOToken ssoToken = new SSOToken();
            ssoToken.setData(accountResult.getData());
            ssoToken.setIp(request);
            SSOHelper.setCookie(request, response, SSOToken.create().setData(accountResult.getData()).setIp(request).setId(1000).setIssuer("sso"), false);
            logger.info("suc","create cookie suc!");
            return ResultGenerator.genSuccessResult(accountResult.getData());
        }else{
            logger.error("error","鉴权错误!");
            return ResultGenerator.genFailResult("鉴权错误!");
        }
    }
}
